import React, { useState } from "react";
import {
  Card,
  Breadcrumb,
  Layout,
  Button,
  Input,
  Row,
  Col,
  Divider,
  Switch,
  Popover,
  Drawer,
  Form,
  Radio,
  Select,
  Popconfirm,
  message,
} from "antd";
import {
  getComponentList,
  getComponentType,
  addComponent,
  editComponent,
  deleteComponent,
} from "../../api/component/index";
import {
  EditOutlined,
  CloseOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";

const { Content } = Layout;
const { Option } = Select;
const componentType = getComponentType();
const style = { background: "#fff", padding: "1px 0" };
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
let set = new Set();
function Home() {
  const [form] = Form.useForm();
  const [ponentList, setPonentList] = useState(getComponentList());

  let existType = [];
  let data = [];
  const [getList, setGetList] = useState([]);
  //筛选条件
  const onClickType = (type) => {
    getList.forEach((e) => {
      existType.push(e.type);
    });
    if (type === "All") {
      setGetList([]);
      set.clear();
      setPonentList(getComponentList());
    } else if (existType.indexOf(type) === -1) {
      // set.add(existType)
      data = [...getList, ...getComponentList().filter((e) => e.type === type)];
      data.forEach((e) => set.add(e.type));
      setPonentList(data);
      setGetList(data);
    } else {
      data = [...getList.filter((e) => e.type !== type)];
      set.delete(type);
      setPonentList(data);
      setGetList(data);
    }
  };
  //输入搜索
  const onChangeSearch = (e) => {
    //将数据都转换为大写再进行比较
    let newlist = getComponentList().filter(
      (item) =>
        item.name.toUpperCase().includes(e.target.value.toUpperCase()) ||
        item.type.toUpperCase().includes(e.target.value.toUpperCase())
    );
    setPonentList(newlist);
  };
  //运行状态
  const [cheCked, setCheCked] = useState("停止");
  //名称修改
  function onChange(checked) {
    setCheCked(checked === false ? "停止" : "启动");
  }
  //添加
  const onFinish = (values) => {
    let data = [
      {
        id: "14308193" + new Date() * 1,
        name: values.componentname,
        type: values.componentype,
        state: {
          text: "已启动",
          value: "enabled",
        },
        creatorId: "admin",
        createTime: new Date() * 1,
        configuration: {
          host: "0.0.0.0",
          port: "9112",
          maxMessageSize: 8096,
        },
        shareCluster: true,
        typeObject: {
          name: "MQTT服务",
          text: "MQTT服务",
          value: "MQTT_SERVER",
        },
      },
    ];

    addComponent(...data);
    setVisibles(false);
  };
  //编辑
  const onReviseFinish = (values) => {
    components.name = values.componentname;
    components.type = values.componentype;
    editComponent(components.id, components);
    setReviseVisibles(false);
    setRefresh({});
  };
  //表单提交失败执行
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  //新增组件弹出
  const [visibles, setVisibles] = useState(false);
  const showDrawer = () => {
    setVisibles(true);
  };
  const onClose = () => {
    setVisibles(false);
  };
  const onReset = () => {
    setVisibles(false);
    form.resetFields();
  };
  //修改组件弹出
  const [Revisevisibles, setReviseVisibles] = useState(false);
  //存储修改的组件信息
  const [components, setComponents] = useState({});
  const showReviseDrawer = (e) => {
    setComponents(e);
    setReviseVisibles(true);
  };
  const onReviseClose = () => {
    setReviseVisibles(false);
  };
  const onReviseReset = () => {
    setReviseVisibles(false);
    form.resetFields();
  };
  //用于强制刷新
  const [_, setRefresh] = useState({});

  //开关确定
  const confirm = (e) => {
    e.state =
      e.state.value === "disabled"
        ? { text: "已启动", value: "enabled" }
        : { text: "已停止", value: "disabled" };
    editComponent(e.id, e);
    setRefresh({});
    // onChange(e.state.value==='disabled')
    message.success(e.state.value === "disabled" ? "关闭成功" : "启动成功");
  };
  //组件删除确定
  const delconfirm = (e) => {
    const componentList = deleteComponent(e.id);
    setPonentList(componentList);
  };
  const cancel = (e) => {
    message.error("取消成功");
  };
  return (
    <>
      <Card>
        <Breadcrumb separator=">">
          <span>组件类型：</span>
          <Button
            onClick={() => onClickType("All")}
            key={"All"}
            style={{ border: "none", fontSize: "5px" }}
          >
            全部
          </Button>
          {componentType.map((item) => {
            return (
              <Button
                onClick={() => onClickType(item.id)}
                key={item.id}
                style={
                  !set.has(item.id)
                    ? {
                        border: "none",
                        fontSize: "5px",
                        color: "rgba(0, 0, 0, 0.85)",
                      }
                    : { border: "none", fontSize: "5px", color: "#1890ff" }
                }
              >
                {item.name}
              </Button>
            );
          })}
          <Divider orientation="left"></Divider>
        </Breadcrumb>
        <Content style={{ margin: "15px 0", padding: "0" }}>
          <span style={{ fontSize: "5px" }}>其他选项：</span>
          <span style={{ marginLeft: "2%", fontSize: "5px" }}>配置名称：</span>

          <Input
            name="type"
            type="text"
            style={{ width: "30%" }}
            onChange={onChangeSearch}
          ></Input>
        </Content>
      </Card>

      <Row gutter={16} style={{ marginTop: "15px" }}>
        <Col className="gutter-row" span={6} style={{ marginTop: "10px" }}>
          <div style={style}>
            <div className="site-card-border-less-wrapper">
              <Card bordered={false}>
                <div style={{ textAlign: "center" }}>
                  <Button
                    icon={<PlusOutlined />}
                    style={{ border: "none", height: "80px", color: "#999" }}
                    onClick={() => showDrawer()}
                  >
                    新增组件
                  </Button>
                  <Drawer
                    title="新增网络组件"
                    placement="right"
                    onClose={onClose}
                    visible={visibles}
                  >
                    <Form
                      form={form}
                      name="basic"
                      layout="horizontal"
                      labelCol={{ span: 8 }}
                      wrapperCol={{ span: 16 }}
                      initialValues={{ remember: true }}
                      onFinish={onFinish}
                      onFinishFailed={onFinishFailed}
                      autoComplete="off"
                    >
                      <Form.Item
                        label="组件名称"
                        name="componentname"
                        rules={[
                          {
                            required: true,
                            message: "请输入名称！",
                          },
                        ]}
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        label="组件类型"
                        name="componentype"
                        rules={[
                          {
                            required: true,
                            message: "请输入类型",
                          },
                        ]}
                      >
                        <Select
                          showSearch
                          optionFilterProp="children"
                          filterOption={(input, option) =>
                            option.children
                              .toLowerCase()
                              .indexOf(input.toLowerCase()) >= 0
                          }
                          filterSort={(optionA, optionB) =>
                            optionA.children
                              .toLowerCase()
                              .localeCompare(optionB.children.toLowerCase())
                          }
                        >
                          {componentType.map((item) => {
                            return (
                              <Option value={item.id} key={item.id}>
                                {item.name}
                              </Option>
                            );
                          })}
                        </Select>
                      </Form.Item>
                      <Form.Item
                        label="集群"
                        name="componenconfigure"
                        rules={[
                          {
                            required: true,
                            message: "请选择配置",
                          },
                        ]}
                      >
                        <Radio.Group name="radiogroup">
                          <Radio value={1}>共享配置</Radio>
                          <Radio value={2}>独立配置</Radio>
                        </Radio.Group>
                      </Form.Item>
                      <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit">
                          确定
                        </Button>
                        <Button htmlType="button" onClick={onReset}>
                          取消
                        </Button>
                      </Form.Item>
                    </Form>
                  </Drawer>
                </div>
              </Card>
            </div>
          </div>
        </Col>
        {ponentList.map((component) => {
          return (
            <Col
              className="gutter-row"
              span={6}
              style={{ marginTop: "10px" }}
              key={component.id}
            >
              <div style={style}>
                <div style={{ display: "flex" }}>
                  <div
                    style={{
                      width: "15px",
                      height: "15px",
                      backgroundColor: "#777",
                      borderRadius: "50%",
                      margin: "15px 15px 5px 15px",
                    }}
                  ></div>
                  <span
                    style={{
                      margin: "13px 0 5px 0",
                      fontSize: "5px",
                      fontWeight: "700",
                    }}
                  >
                    {/* 组件名称 */}
                    {component.name}
                  </span>
                </div>
                <div style={{ display: "flex" }}>
                  <div
                    style={{
                      margin: "10px 35px",
                      fontSize: "3px",
                      textAlign: "center",
                      color: "#777",
                    }}
                  >
                    {/* 组件类型 */}
                    <div>组件类型</div>
                    <div style={{ color: "#000" }}>{component.type}</div>
                  </div>
                  <div
                    style={{
                      margin: "10px 35px",
                      fontSize: "3px",
                      textAlign: "center",
                      color: "#777",
                    }}
                  >
                    <div>启动状态</div>
                    <Popconfirm
                      title={"确定" + cheCked}
                      onConfirm={() => confirm(component)}
                      onCancel={() => cancel(component)}
                      okText="确定"
                      cancelText="取消"
                    >
                      <a href="#">
                        <Switch
                          onChange={onChange}
                          size="small"
                          checked={component.state.value === "enabled"}
                        />
                      </a>
                    </Popconfirm>
                  </div>
                </div>
                <Divider style={{ margin: "0px" }}></Divider>
                {/* 组件修改 */}

                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => showReviseDrawer(component)}
                  style={{
                    width: "50%",
                    color: "#777",
                    backgroundColor: "#fafafa",
                  }}
                />
                {/* 组件删除 */}
                <Popconfirm
                  title={"确定删除组件吗？"}
                  onConfirm={() => delconfirm(component)}
                  onCancel={cancel}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="link"
                    icon={<CloseOutlined />}
                    style={{
                      width: "50%",
                      color: "#777",
                      backgroundColor: "#fafafa",
                    }}
                  />
                </Popconfirm>
              </div>
            </Col>
          );
        })}
        {/* 修改组件表单 */}
        <Drawer
          title="编辑网络组件"
          placement="right"
          onClose={onReviseClose}
          visible={Revisevisibles}
        >
          <Form
            form={form}
            name="basic"
            layout="horizontal"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onReviseFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="组件名称"
              name="componentname"
              rules={[
                {
                  required: true,
                  message: "请输入名称！",
                },
              ]}
            >
              <Input defaultValue={components.name} />
            </Form.Item>
            <Form.Item
              label="组件类型"
              name="componentype"
              rules={[
                {
                  required: true,
                  message: "请输入类型",
                },
              ]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                placeholder={components.type}
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
                filterSort={(optionA, optionB) =>
                  optionA.children
                    .toLowerCase()
                    .localeCompare(optionB.children.toLowerCase())
                }
              >
                {componentType.map((item) => {
                  return (
                    <Option value={item.id} key={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="集群"
              name="componenconfigure"
              rules={[
                {
                  required: true,
                  message: "请选择配置",
                },
              ]}
            >
              <Radio.Group name="radiogroup" defaultValue={1}>
                <Radio value={1}>共享配置</Radio>
                <Radio value={2}>独立配置</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button htmlType="button" onClick={onReviseReset}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Drawer>
      </Row>
    </>
  );
}

export default Home;
